package com.b2b.controller.system;

import com.b2b.exception.CustomException;
import com.b2b.exception.CustomUnauthorizedException;
import com.b2b.model.*;
import com.b2b.model.common.BaseDto;
import com.b2b.model.common.ResponseBean;
import com.b2b.model.entity.Notice;
import com.b2b.model.entity.User;
import com.b2b.model.receive.CompanyId;
import com.b2b.model.receive.InfoDto;
import com.b2b.model.receive.QuotationFromI;
import com.b2b.service.NoticeService;
import com.b2b.service.UserService;
import com.b2b.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@PropertySource("classpath:config.properties")
public class AdminSystemController {

    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    private final BiddingUtil biddingUtil;
    private final InquiryUtil inquiryUtil;
    private final GoodsUtil goodsUtil;
    private final QuotationUtil quotationUtil;
    private final UserUtil userUtil;
    private final UserService userService;
    private final ContractUtil contractUtil;
    private final ShopUtil shopUtil;
    private final CompanyApiAuthorityUtil companyApiAuthorityUtil;
    private final NoticeService noticeService;
    public AdminSystemController(CompanyApiAuthorityUtil companyApiAuthorityUtil, UserUtil userUtil,
                                 UserService userService, ContractUtil contractUtil, ShopUtil shopUtil,
                                 BiddingUtil biddingUtil, InquiryUtil inquiryUtil, GoodsUtil goodsUtil,
                                 QuotationUtil quotationUtil,NoticeService noticeService
                                 ){
        this.companyApiAuthorityUtil = companyApiAuthorityUtil;
        this.userUtil = userUtil;
        this.userService = userService;
        this.contractUtil = contractUtil;
        this.shopUtil = shopUtil;
        this.biddingUtil = biddingUtil;
        this.inquiryUtil = inquiryUtil;
        this.goodsUtil = goodsUtil;
        this.quotationUtil = quotationUtil;
        this.noticeService = noticeService;
    }


    @GetMapping("/user")
    public ResponseBean getUser(InfoDto infoDto){
        if (infoDto.getId()==null && infoDto.getName()==null){
            PageHelper.startPage(infoDto.getPage(), infoDto.getRows());
            List<User> userList = userUtil.getAll();
            PageInfo<User> selectPage = new PageInfo<User>(userList);
            if (userList == null || userList.size() < 0) {
                throw new CustomException("查询失败(Query Failure)");
            }
            Map<String, Object> result = new HashMap<String, Object>(16);
            result.put("count", selectPage.getTotal());
            result.put("data", selectPage.getList());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
        }else if (infoDto.getId()==null){
            User user = userUtil.getUserByName(infoDto.getName());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", user);
        }else {
            User user = userUtil.getUser(infoDto.getId());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", user);
        }
    }

    @PutMapping("/user")
    public ResponseBean updateUserState(@RequestBody User user){
        User userDto = new User();
        userDto.setUserId(user.getUserId());
        Integer count = userService.selectCount(userDto);
        if (count <=0){
            throw new CustomException("用户不存在");
        }
        userDto.setState(user.getState());
        count = userService.updateByPrimaryKeySelective(userDto);
        if (count <=0){
            throw new CustomException("修改失败(Update Failure)");
        }

        return new ResponseBean(HttpStatus.OK.value(), "修改成功(Update was successful)", null);
    }

    @PostMapping("/addContract")
    public ResponseBean addContract(@RequestBody ContractDto contractDto){

        char state = '0';

        contractDto.setVisibility(state);
        contractDto.setCompanyId(0);
        Integer count = contractUtil.addContract(contractDto);
        if (count <= 0) {
            throw new CustomException("插入失败(Insert Failure)");
        }


        return new ResponseBean(HttpStatus.OK.value(), "上传成功！", contractDto);
    }
    @GetMapping("/getContract")
    public ResponseBean getContract(InfoDto infoDto){
        if (infoDto.getName()==null){
            if (infoDto.getPage() == null || infoDto.getRows() == null) {
                infoDto.setPage(1);
                infoDto.setRows(10);
            }
            PageHelper.startPage(infoDto.getPage(), infoDto.getRows());
            List<ContractDto> contractList = contractUtil.getAll();
            PageInfo<ContractDto> selectPage = new PageInfo<ContractDto>(contractList);
            if (contractList == null) {
                throw new CustomException("查询失败(Query Failure)");
            }
            Map<String, Object> result = new HashMap<String, Object>(16);
            result.put("count", selectPage.getTotal());
            result.put("data", selectPage.getList());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
        }else {
            ContractDto contract = contractUtil.getByName(infoDto.getName());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", contract);
        }
    }


    @GetMapping("/getShop")
    public ResponseBean getShop(InfoDto infoDto){
        String stateDto = infoDto.getState();
        if (infoDto.getName()==null&&infoDto.getId()==null&&infoDto.getState()==null){
            if (infoDto.getPage() == null || infoDto.getRows() == null) {
                infoDto.setPage(1);
                infoDto.setRows(10);
            }
            PageHelper.startPage(infoDto.getPage(), infoDto.getRows());
            List<ShopDto> shopList = shopUtil.getAllShop();
            PageInfo<ShopDto> selectPage = new PageInfo<ShopDto>(shopList);
            Map<String, Object> result = new HashMap<String, Object>(16);
            result.put("count", selectPage.getTotal());
            result.put("shopList", selectPage.getList());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
        }else if (infoDto.getName().equals("")&&infoDto.getId()==null){
            if (infoDto.getPage() == null || infoDto.getRows() == null) {
                infoDto.setPage(1);
                infoDto.setRows(10);
            }
            PageHelper.startPage(infoDto.getPage(), infoDto.getRows());
            char state = infoDto.getState().charAt(0);
            List<ShopDto> shopList = shopUtil.getShopByState(state);
            PageInfo<ShopDto> selectPage = new PageInfo<ShopDto>(shopList);
            if (shopList == null || shopList.size() < 0) {
                throw new CustomException("查询失败(Query Failure)");
            }
            Map<String, Object> result = new HashMap<String, Object>(16);
            result.put("count", selectPage.getTotal());
            result.put("shopList", selectPage.getList());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
        }else if (infoDto.getName().equals("")){
            ShopDto shop = shopUtil.getShopById(infoDto.getId());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", shop);
        }else {
            ShopDto shop = shopUtil.getShopByName(infoDto.getName());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", shop);
        }
    }


    @PutMapping("/banShop")
    public ResponseBean updateShopState(@RequestBody InfoDto infoDto){
        ShopDto shopDto = new ShopDto();
        if (infoDto.getId()==null){
            throw new CustomException("更新失败(Update Failure)");
        }
        char state = infoDto.getState().charAt(0);
        shopDto.setShopId(infoDto.getId());
        shopDto.setState(state);
        Integer count = shopUtil.updateShopState(shopDto);
        if (count<=0){
            throw new CustomException("更新失败(Update Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update was successful)", null);
    }

    /**
     * 新增公司API权限
     * @param companyApiAuthorityDto
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:42
     */
    @PostMapping("/addCompanyAPI")
//    @RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
    public ResponseBean add(@RequestBody CompanyApiAuthorityDto companyApiAuthorityDto) {
        int count = companyApiAuthorityUtil.insertAPI(companyApiAuthorityDto);
        if (count == -2) {
            throw new CustomUnauthorizedException("该API名称已存在(Account exist.)");
        }
        if (count <= 0) {
            throw new CustomException("新增失败(Insert Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", companyApiAuthorityDto);
    }

    /**
     * 获取公司API权限
     * @param
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:42
     */
    @GetMapping("/getCompanyAPI")
    //@RequiresPermissions(logical = Logical.AND, value = {"user:view"})
    public ResponseBean findAll(InfoDto infoDto) {
        if (infoDto.getId()==null) {
            if (infoDto.getPage() == null || infoDto.getRows() == null) {
                infoDto.setPage(1);
                infoDto.setRows(10);
            }
            PageHelper.startPage(infoDto.getPage(), infoDto.getRows());
            List<CompanyApiAuthorityDto> companyApiAuthorityDtos = companyApiAuthorityUtil.getAll();
            PageInfo<CompanyApiAuthorityDto> selectPage = new PageInfo<CompanyApiAuthorityDto>(companyApiAuthorityDtos);
            if (companyApiAuthorityDtos == null) {
                throw new CustomException("查询失败(Query Failure)!");
            }
            Map<String, Object> result = new HashMap<String, Object>(16);
            result.put("count", selectPage.getTotal());
            result.put("data", selectPage.getList());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
        }else {
            CompanyApiAuthorityDto companyApiAuthorityDto = companyApiAuthorityUtil.getById(infoDto.getId());
            return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", companyApiAuthorityDto);
        }
    }

    /**
     * 更新公司API权限
     * @param companyApiAuthorityDto
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:42
     */
    @PutMapping("/updateCompanyAPI")
    //@RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
    public ResponseBean update( @RequestBody CompanyApiAuthorityDto companyApiAuthorityDto) {
        // 查询数据库密码
        int count = companyApiAuthorityUtil.update(companyApiAuthorityDto);
        if (count == -2) {
            throw new CustomUnauthorizedException("该帐号不存在(Account not exist.)");
        }
        if (count <= 0) {
            throw new CustomException("更新失败(Update Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update Success)", companyApiAuthorityDto);
    }

    /**
     * 删除相关公司API权限
     * @param companyId
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     * @date 2018/8/30 10:43
     */
    @DeleteMapping("/deleteCompanyAPI")
    // @RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
    public ResponseBean delete(CompanyId companyId) {
        int count = companyApiAuthorityUtil.delete(companyId.getCompanyId());
        if (count <= 0) {
            throw new CustomException("删除失败，ID不存在(Deletion Failed. ID does not exist.)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "删除成功(Delete Success)", null);
    }


    @GetMapping("/getBidding")
    public ResponseBean getBiddingList(BaseDto baseDto){
        if (baseDto.getPage() == null || baseDto.getRows() == null) {
            baseDto.setPage(1);
            baseDto.setRows(10);
        }
        PageHelper.startPage(baseDto.getPage(), baseDto.getRows());
        List<BiddingDto> biddingList = biddingUtil.getBiddingList();
        PageInfo<BiddingDto> selectPage = new PageInfo<BiddingDto>(biddingList);
        if (biddingList == null) {
            throw new CustomException("查询失败(Query Failure)!");
        }
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("count", selectPage.getTotal());
        result.put("data", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }


    @GetMapping("/getBiddingRecord")
    public ResponseBean getBiddingRecord(@RequestParam Integer biddingId){
        List<BiddingRecordDto> biddingRecordList = biddingUtil.getBiddingRecord(biddingId);
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Select Success)", biddingRecordList);
    }

    @GetMapping("/getInquiry")
    public ResponseBean getAll(InquiryConditionDto baseDto){
        if (baseDto.getPage() == null || baseDto.getRows() == null) {
            baseDto.setPage(1);
            baseDto.setRows(10);
        }
        PageHelper.startPage(baseDto.getPage(), baseDto.getRows());
        List<InquiryRoughDto> inquiryRoughDtoList = inquiryUtil.getByCondition(baseDto);
        PageInfo<InquiryRoughDto> selectPage = new PageInfo<InquiryRoughDto>(inquiryRoughDtoList);
        if (inquiryRoughDtoList == null || inquiryRoughDtoList.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("count", selectPage.getTotal());
        result.put("data", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    @GetMapping("/getInquiryDetail")
    public ResponseBean getInquiry(@RequestParam Integer inquiryId){
//        Integer inquiryId = inquiryMaterial.getInquiryId();
//        Inquiry inquiry = inquiryUtil.selectInquiry(inquiryId);
        Map<String,Object> result = inquiryUtil.selectByInquiry(inquiryId);
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

//    @GetMapping("/getQuotation")
//    public ResponseBean getQuotationByCFromI(InfoDto infoDto){
//        Integer inquiryId = infoDto.getId();
//        if (inquiryId ==null){
//            throw new CustomException("InquiryQuotation 查询失败(Select Failure)");
//        }
//        PageHelper.startPage(infoDto.getPage(), infoDto.getRows());
//        List<QuotationFromI> quotationFromIS = quotationUtil.selectByInquiryIdFromA(inquiryId);
//        PageInfo<QuotationFromI> selectPage = new PageInfo<QuotationFromI>(quotationFromIS);
//        if (quotationFromIS == null || quotationFromIS.size() < 0) {
//            throw new CustomException("查询失败(Query Failure)");
//        }
//        Map<String, Object> result = new HashMap<String, Object>(16);
//        result.put("count", selectPage.getTotal());
//        result.put("data", selectPage.getList());
//        return new ResponseBean(HttpStatus.OK.value(),"查询成功(Select Success)",result);
//    }

    @PostMapping("/addNotice")
    public ResponseBean addNotice(@RequestBody Notice notice){
        Notice noticeTemp = new Notice();
        noticeTemp.setTitle(notice.getTitle());
        int count = noticeService.selectCount(noticeTemp);
        if (count > 0){
            throw new CustomException("标题重复");
        }
        count = noticeService.insert(notice);
        if (count < 0 ){
            throw new CustomException("Insert Fail 插入失败");
        }
        return new ResponseBean(HttpStatus.OK.value(),"查询成功(Select Success)",null);
    }

    @DeleteMapping("/deleteNotice")
    public ResponseBean deleteNotice(@RequestParam Integer noticeId){
        Notice noticeTemp = new Notice();
        noticeTemp.setNoticeId(noticeId);
        int count = noticeService.selectCount(noticeTemp);
        if (count <= 0){
            throw new CustomException("Not Exist");
        }
        count = noticeService.deleteByPrimaryKey(noticeId);
        if (count < 0 ){
            throw new CustomException("Delete Fail 删除失败");
        }
        return new ResponseBean(HttpStatus.OK.value(),"删除成功(Delete Success)",null);
    }

    @PutMapping("/updateNotice")
    public ResponseBean updateNotice(@RequestBody Notice notice){
        Notice noticeTemp = new Notice();
        noticeTemp.setTitle(notice.getTitle());
        int count = noticeService.selectCount(noticeTemp);
        if (count > 0){
            throw new CustomException("标题重复");
        }
        count = noticeService.updateByPrimaryKeySelective(notice);
        if (count < 0 ){
            throw new CustomException("Update Fail 更新失败");
        }
        return new ResponseBean(HttpStatus.OK.value(),"更新成功(Update Success)",null);
    }
}
